package com.codingfly.controller;

import cn.hutool.core.bean.BeanUtil;
import com.codingfly.controller.common.BaseController;
import com.codingfly.core.exception.BizException;
import com.codingfly.core.util.AssertUtils;
import com.codingfly.core.util.TreeListUtils;
import com.codingfly.entity.SysGroup;
import com.codingfly.model.Result;
import com.codingfly.model.dto.GroupDto;
import com.codingfly.model.vo.GroupVo;
import com.codingfly.service.SysGroupService;
import com.codingfly.service.impl.CommonServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@RestController
@RequestMapping("/group")
public class GroupController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(GroupController.class);
    @Autowired
    private SysGroupService sysGroupService;
    @Autowired
    private CommonServiceImpl commonServiceImpl;

    public Set<Integer> typeSet = new HashSet() {{ add(1); add(2); }};

    @PostMapping
    public Result add(@RequestBody GroupDto dto) {
        checkParams(dto, "type", "name", "code", "parentId", "auditTime");
        AssertUtils.isTrue(typeSet.contains(dto.getType()), "type取值只能是1或者2");
        SysGroup codeSysGroup = sysGroupService.findByCode(dto.getCode());
        AssertUtils.isTrue(codeSysGroup==null, "该code编码 "+dto.getCode()+" 的数据已存在");
        SysGroup parent = Optional.ofNullable(sysGroupService.findById(dto.getParentId())).orElseThrow(()->new BizException("父节点不存在或者已删除"));
        AssertUtils.isTrue(new Integer(2).equals(parent.getType()), "父级是部门，不能挂子级机构");
        SysGroup sysGroup = new SysGroup();
        sysGroup.setType(dto.getType());
        sysGroup.setName(dto.getName());
        sysGroup.setCode(dto.getCode());
        sysGroup.setAuditTime(dto.getAuditTime());
        sysGroup.setParentId(dto.getParentId());
        sysGroup.setOrderNo(commonServiceImpl.queryNextOrderNoInt("sys_group"));
        sysGroupService.save(sysGroup);
        Integer id = sysGroup.getId();
        sysGroup.setFullPath(parent.getFullPath()+","+id);
        sysGroupService.save(sysGroup);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable("id") Integer id, @RequestBody GroupDto dto) {
        checkParams(dto, "code", "name", "auditTime");
        SysGroup group = Optional.ofNullable(sysGroupService.findById(id)).orElseThrow(()->new BizException("该节点不存在或者已删除"));
        if (!dto.getCode().equals(group.getCode())) {
            AssertUtils.isTrue(sysGroupService.findByCode(dto.getCode())==null, "该CODE编码 "+dto.getCode()+" 已存在");
        }
        group.setCode(dto.getCode());
        group.setName(dto.getName());
        group.setAuditTime(dto.getAuditTime());
        sysGroupService.save(group);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer id) {
        AssertUtils.isTrue(!sysGroupService.hasChildren(id), "请先删除子节点");
        sysGroupService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<SysGroup> queryById(@PathVariable("id") Integer id) {
        return Result.success(sysGroupService.findById(id));
    }

    @GetMapping("/treeList")
    public Result<List<SysGroup>> queryTreeList() {
        List<SysGroup> sysGroups = sysGroupService.findAll();
        List<GroupVo> groupVos = BeanUtil.copyToList(sysGroups, GroupVo.class);
        groupVos = TreeListUtils.buildAscTreeList(groupVos, "id", "parentId", "children", "orderNo");
        return Result.success(groupVos);
    }

    @PatchMapping("/move/{id}")
    public Result move(@PathVariable("id") Integer id, @RequestParam("action") String action) {
        if ("up".equals(action)) {
            commonServiceImpl.upOrderNoHasParent("sys_group", id);
        } else if ("down".equals(action)) {
            commonServiceImpl.downOrderNoHasParent("sys_group", id);
        }
        return Result.success();
    }

}
